package com.amorcloud.pig.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.rscja.deviceapi.RFIDWithUHF;

import tool.EpcCrypto;

public class RFIDUtil {

    public RFIDWithUHF mReader;
    EditText editText;
    Context context;

    public RFIDUtil(View view, Context context) {
        this.context = context;
        editText = (EditText) view;
        try {
            mReader = RFIDWithUHF.getInstance();
        } catch (Exception ex) {
            ex.printStackTrace();
            return;
        }

        if (mReader != null) {
            new InitTask().execute();
        }
    }

    public void startRead() {
        String strUII = mReader.inventorySingleTag();
        if (!TextUtils.isEmpty(strUII)) {
            Log.d("leihuiming","original data = " + strUII);
            //strUII = mReader.convertUiiToEPC(strUII);
            //strUII = Decode.GetDecodeEpc(strUII);

            strUII = strUII.substring(4, strUII.length());
            Log.d("leihuiming", "strUII substring = " + strUII);
            strUII = EpcCrypto.Decode(strUII);
            Log.d("leihuiming","EPC decode = " + strUII);
            if(strUII != null) {
                editText.setText(strUII);
            } else {
                Toast.makeText(context, "数据解析错误", Toast.LENGTH_SHORT).show();
            }

        }
    }

    public class InitTask extends AsyncTask<String, Integer, Boolean> {
        ProgressDialog mypDialog;

        @Override
        protected Boolean doInBackground(String... params) {
            // TODO Auto-generated method stub
            return mReader.init();
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);

            mypDialog.cancel();

            if (!result) {
                Toast.makeText(context, "RFID初始化失败", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            mypDialog = new ProgressDialog(context);
            mypDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mypDialog.setMessage("init...");
            mypDialog.setCanceledOnTouchOutside(false);
            mypDialog.show();
        }
    }

    public void closeRFID() {
        if(mReader != null) {
            mReader.free();
        }
    }
}
